package com.zk.spring5.dao;

import com.zk.spring5.bean.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author ZK
 * @Description
 * @time 2021/5/5 22:41
 * @note
 */
@Repository
public class UserDaoImpl implements UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public int addUser(User user) {
        String sql = "insert into t_user(username,status) values(?,?);";
        return jdbcTemplate.update(sql, user.getUsername(), user.getStatus());
    }

    @Override
    public int updateUser(User user) {
        String sql = "update t_user set username=?, status=? where user_id=?";
        return jdbcTemplate.update(sql,user.getUsername(),user.getStatus(),user.getUserId());
    }

    @Override
    public int deleteUser(Integer userId) {
        String sql = "delete from t_user where user_id = ?;";
        return jdbcTemplate.update(sql,userId);
    }

    @Override
    public int getCount() {
        String sql = "select count(*) from t_user;";
        return jdbcTemplate.queryForObject(sql,int.class);
    }

    @Override
    public User getOneUserById(Integer userId) {
        String sql = "select * from t_user where user_id = ?";
        RowMapper<User> rw = new BeanPropertyRowMapper<>(User.class);
        return jdbcTemplate.queryForObject(sql,rw,userId);
    }

    @Override
    public List<User> getAllUsers() {
        String sql = "select * from t_user;";
        List<User> users = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
        return users;
    }

    @Override
    public int[] batchAddUsers(List<Object[]> batchArgs) {
        String sql = "insert into t_user(username,status) values(?,?);";
        return jdbcTemplate.batchUpdate(sql,batchArgs);
    }

    @Override
    public int[] batchDeleteUsers(List<Object[]> batchArgs) {
        String sql = "delete from t_user where user_id = ?;";
        return jdbcTemplate.batchUpdate(sql,batchArgs);
    }

    @Override
    public int[] batchUpdateUsers(List<Object[]> batchArgs) {
        String sql = "update t_user set username=?, status=? where user_id=?;";
        return jdbcTemplate.batchUpdate(sql,batchArgs);
    }


}
